package com.dl.interceptor;

import com.dl.pojo.User;
import com.dl.service.UserService;
import com.dl.utils.ConstantField;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.FlashMap;
import org.springframework.web.servlet.FlashMapManager;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * @author DL
 * @create 2021-03-16 14:20
 */
@Component
public class RememberMeInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;

    //return true ：执行下一个拦截器，放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        String originUri = request.getRequestURI();
        //对uri进行转码
        String uri = URLDecoder.decode(originUri, "utf-8");
        System.out.println("request.getRequestURI()=>" + uri);

        Subject subject = SecurityUtils.getSubject();
        System.out.println("subject.isRemembered() = " + subject.isRemembered());
        if (!subject.isAuthenticated() && subject.isRemembered()){
            System.out.println("未认证但以记住状态");
            String username = (String) subject.getPrincipal();
            User user = userService.queryUserByName(username);
            System.out.println("user.getPassword() = " + user.getPassword());

            //UsernamePasswordToken token = new UsernamePasswordToken();
            //subject.login(token);
            Session shiroSession = subject.getSession();
            shiroSession.setAttribute(ConstantField.LOGIN_INFO, user);
            return true;
        }
        return true;
    }
}
